package de.fzi.kasma.learner.gui;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;

import ec.Evolve;

public class RunTab implements SelectionListener{
	
	public Button runButton;
//	public Button stopButton;
	public TabItem tab;
	public StartGui startGUI;
	public Text textWidget;
	public Group group;
	AlgorithmThread algorithmThread;
	String[] params;
	

	private class AlgorithmThread extends Thread {
		
		private long startTime;
		private long endTime;
		
		@Override
		public void run() {
			startTime = System.nanoTime();
//			setPriority(Thread.MIN_PRIORITY);

			try {
				Evolve.main(params);
//				Main.main(new String[3]);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			endTime = System.nanoTime();
		}
		
		public long getRuntimeNanos() {
			if(isAlive()) {
//				System.out.println("ALIVE");
				return System.nanoTime() - startTime;
			} else {
//				System.out.println("NOT ALIVE");
				return endTime - startTime;
			}
		}		
	}




	public RunTab(StartGui startGui2, TabFolder parent, int style) {
		
		 tab = new TabItem(parent, style);
         startGUI = startGui2;


		tab.setText ("Run");
		group = new Group (parent, SWT.SHADOW_OUT);
		GridLayout gridLayout = new GridLayout ();
		gridLayout.numColumns = 2;
		group.setLayout (gridLayout);
		group.setText ("Learning results");
		


		//Result area
		
		textWidget = new Text(group, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
		GridData gridData = new GridData (GridData.FILL_BOTH);
		textWidget.setLayoutData (gridData);	

		Group group1 = new Group (group, SWT.SHADOW_OUT);
		GridLayout grid= new GridLayout ();
		grid.numColumns = 1;
		group1.setLayout (grid);
		
	    runButton = new Button(group1, SWT.VERTICAL);
	    runButton.setText("Run");

		runButton.addSelectionListener(this);
		
		

//	    stopButton = new Button(group1, SWT.VERTICAL);
//	    stopButton.setText("Stop");
//	    SelectionListener stopListener = new SelectionListener() {
//			
//			@Override
//			public void widgetSelected(SelectionEvent e) {			
//				stopRDFLearner();			
//			}
//			
//			@Override
//			public void widgetDefaultSelected(SelectionEvent e) {
//				widgetSelected(e);
//				
//			}
//		};;;
//		stopButton.addSelectionListener(stopListener );
		
		tab.setControl(group);

	}
	
	  protected void stopRDFLearner() {


		
	}

	public void showStats() {
	
		
		File file = new File("out.stat");
        StringBuffer contents = new StringBuffer();
        BufferedReader reader = null;

        try
        {
            reader = new BufferedReader(new FileReader(file));
            String text = null;


            // repeat until all lines is read
            while ((text = reader.readLine()) != null)
            {	
            	if(text.endsWith("Best Individual of Run:")){
//                    contents.append(text)
            		contents.append(System.getProperty(
                        "line.separator"));break;
            	}
            }
            while ((text = reader.readLine()) != null){
                contents.append(text)
                    .append(System.getProperty(
                        "line.separator"));
            }
            contents.append(System.getProperty("line.separator"));
            
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        } finally
        {
            try
            {
                if (reader != null)
                {
                    reader.close();
                }
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
		long algorithmRunTime = algorithmThread.getRuntimeNanos();
		textWidget.append("Total running time: "+makeTime(algorithmRunTime) + Text.DELIMITER);
		
        textWidget.append(contents.toString());

        runButton.setEnabled(true);
		
	}

	private String makeTime(Long nanoSeconds) {
		if (nanoSeconds == null)
			return null;
		Long hours = 0L, minutes = 0L, seconds = 0L, millis = 0L; 
		String timeStr = "";

		nanoSeconds /= 1000;
		nanoSeconds /= 1000;
		millis = nanoSeconds % 1000;
		nanoSeconds /= 1000;
		seconds = nanoSeconds % 60;
		nanoSeconds /= 60;
		minutes = nanoSeconds % 60;
		nanoSeconds /= 60;
		hours = nanoSeconds;

		if (hours > 0)
			timeStr += hours + "h ";
		if (minutes > 0)
			timeStr += minutes + "min ";
		if (seconds > 0)
			timeStr += seconds + "s ";
		if (millis > 0)
			timeStr += millis + "ms ";
		return timeStr;
	}




	@Override
	public void widgetDefaultSelected(SelectionEvent e) {
		widgetSelected(e);
		
	}

	@Override
	public void widgetSelected(SelectionEvent arg0) {
		
		// start
            params = getParams();
//            for(String s : params){
//            	System.out.println(s);
//            }
			algorithmThread = new AlgorithmThread();
			algorithmThread.start();
			runButton.setEnabled(false);
//			stopButton.setEnabled(true);
			while (algorithmThread.isAlive()) {

			}
			showStats();
		
	}

	private String[] getParams() {

		
		String [] ilpParams = startGUI.ilpTab.getParams();
		String [] epParams = startGUI.epTab.getParams();
		String [] parameter = new String[ilpParams.length+epParams.length];
		
		for(int i = 0; i<ilpParams.length; i++){
			parameter[i] = ilpParams[i];
		}
		
		for(int i = ilpParams.length; i<parameter.length; i++){
			parameter[i] = epParams[i-ilpParams.length];
		}
		
		String [] params = new String[parameter.length*2+2];
		params[0] = "-file";
		params[1] = "src/de/fzi/kasma/learner/genetic/rl.params";
			
		for(int i = 2, j=0; i<params.length; i+=2, j++){
			params[i] = "-p";
			params[i+1] = parameter[j];
		}
		
		return params;
		
	}


}
